package cn.org.timespace.ons.dao.base.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.org.timespace.ons.action.base.AppleServerModel;
import cn.org.timespace.ons.dao.TSBaseDAO;
import cn.org.timespace.ons.dao.base.AppleServerDao;
import cn.org.timespace.ons.util.pager.Pager;
import cn.org.timespace.ons.vo.base.AppleServer;
import cn.org.timespace.ons.vo.base.Options;
import cn.org.timespace.ons.vo.base.UserMachineType;



public class AppleServerDaoImpl extends TSBaseDAO implements AppleServerDao{

	@Override
	public List<AppleServer> findByCondition(AppleServerModel model) {
		// TODO Auto-generated method stub
		StringBuffer queryString = new StringBuffer("from AppleServer a where 1=1");

		
		
		if(!StringUtils.isEmpty(model.getAsid())){
			queryString.append(" and a.asid = '" + model.getCompCode()
					+ "'");
		}

		queryString.append(" order by a.asid desc");

		return getHibernateTemplate().find(queryString.toString());
	}
	public List<Object> findByCondition(AppleServerModel model,Pager p) {
		log.debug("finding all EfUserLoginLog instances");
		
		Session session = null;
		Query query = null;
		try {
			StringBuffer queryString = new StringBuffer("select a.name,a.status,a.address,a.remark,a.asid,a.interType,a.interAddress ,a.interMethod from AppleServer a where 1=1 ");
			
			if (!StringUtils.isEmpty(model.getTheIdUserApply())) {
				queryString.append(" and a.theIdUserApply = '" + model.getTheIdUserApply().trim()
						+ "'");
			}
			
			if (!StringUtils.isEmpty(model.getUserName())) {
				queryString.append(" and a.userName = '" + model.getUserName().trim()
						+ "'");
			}
			if(model.getName()!=null && !(model.getName().equals(""))){
				queryString.append(" and a.name like '%" + model.getName().trim()+"%'");
			}
			queryString.append(" and a.status = " + model.getStatus());
			queryString.append(" order by a.asid desc ");
			
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			
			
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			
			setQueryPager(query, p);
			
			List list = new ArrayList();
			for(int i = 0;i < query.list().size();i++){
				Object[] obj=(Object[])query.list().get(i);
				AppleServer appleServer = new AppleServer();
				
				appleServer.setName((obj[0].toString()));
				appleServer.setStatus(Integer.parseInt(obj[1].toString()));
				appleServer.setAddress(obj[2].toString());
				appleServer.setRemark(obj[3].toString());
				appleServer.setAsid((((obj[4].toString()))));
				appleServer.setInterType(obj[5].toString());
				appleServer.setInterAddress(obj[6].toString());
				appleServer.setInterMethod(obj[7].toString());
				list.add(appleServer);
			}
			resList.add(list);
			
			return resList;
			
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}
	
	
	public List<Object> findByCondition(Pager p) {
		log.debug("finding all EfUserLoginLog instances");
		
		Session session = null;
		Query query = null;
		try {
			StringBuffer queryString = new StringBuffer("from AppleServer a where 1 = 1");
			
			queryString.append(" order by a.asid desc ");
			
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			setQueryPager(query, p);
			resList.add(query.list());
			return resList;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}
	
	
	/**
	 * 终端服务在选择增加应用时，根据已增加的应用id，不显示已增加的应用
	 * @param asid 已增加的应用id
	 * @param p 分页
	 * @return
	 */
	public List<Object> notShowExistApp(String[] asid,Pager p) {
		log.debug("finding all EfUserLoginLog instances");
		
		Session session = null;
		Query query = null;
		try {
			StringBuffer queryString = new StringBuffer("from AppleServer a where 1 = 1");
			
			if(asid!=null){
				queryString.append(" and a.asid not in ('");//不显示条件
				int i;
				for( i=0 ;i<asid.length;i++){
					queryString.append(asid[i]);
					queryString.append("'");
					
					if(i<asid.length-1){
						queryString.append(",");
					}
				}
				queryString.append(")");
			}
			
			
			queryString.append(" order by a.asid desc ");
			
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			setQueryPager(query, p);
			resList.add(query.list());
			return resList;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}
	
	
	
	

	public void save(AppleServer transientInstance) {
		log.debug("saving AppleServer instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(AppleServer persistentInstance) {
		log.debug("deleting AppleServer instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public AppleServer findById(java.lang.String asid) {
		log.debug("getting AppleServer instance with id: " + asid);
		try {
			AppleServer instance = (AppleServer) getHibernateTemplate().get(
					"cn.org.timespace.ons.vo.base.AppleServer", asid);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public void update(AppleServer instance) {
		try {
			getHibernateTemplate().update(instance);
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	
	public AppleServer findByCompCode(String name) {
		StringBuffer queryString = new StringBuffer("from AppleServer a where a.name = '"+name+"'");
		List<AppleServer> resList = getHibernateTemplate().find(queryString.toString());
		if(resList != null && resList.size() == 1){
			return resList.get(0);
		}
		return null;
	}
	
	@Override
	public List<Options> findByCode(String name) {
		log.debug("finding all findByCode instances");
	    String hql = "from Options o where name='"+name+"'";
	    return (List<Options>) this.getHibernateTemplate().find(hql);
	}
	
	@Override
	public AppleServer findByCondition(String IP, String port) {
		// TODO Auto-generated method stub
		StringBuffer queryString = new StringBuffer("from AppleServer a where 1=1");
		
		queryString.append(" and a.ipAddress ='" +IP+ "'");
	
		queryString.append(" and a.port ='" +port+ "'");
	
	
	
	List<AppleServer> resList = getHibernateTemplate().find(queryString.toString());
	if(resList != null && resList.size() == 1){
		return resList.get(0);
	}
	return null;
	}
	//我的申请先列出现有的应用，先有应用在我的终端类型里没有记录
	public List<Object> findAppByCondition(String theidname[],Pager p) {
		log.debug("finding all EfUserLoginLog instances");
		
		Session session = null;
		Query query = null;
		try {
			StringBuffer queryString = new StringBuffer("select a.name,a.status,a.address,a.remark,a.asid,a.interType,a.interAddress ,a.interMethod ,eu.userAccount,eu.compName" +
					" from AppleServer a ,EfUser eu where 1=1 and a.userName = eu.userAccount");
			
			queryString.append(" and a.asid not in(select ta.theIdapply from TypeAudit  ta,UserMachineType ut " +
					"where ta.theIdmachine=ut.theIdMachine and ta.theIdmachine='"+theidname[0]+"' and ta.startUserName='"+theidname[1]+"') ");
			queryString.append(" and a.status = 1" );
			queryString.append(" order by a.asid desc ");
			
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			
			
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			
			setQueryPager(query, p);
			
			List list = new ArrayList();
			for(int i = 0;i < query.list().size();i++){
				Object[] obj=(Object[])query.list().get(i);
				AppleServer appleServer = new AppleServer();
				
				appleServer.setName((obj[0].toString()));
				appleServer.setStatus(Integer.parseInt(obj[1].toString()));
				appleServer.setAddress(obj[2].toString());
				appleServer.setRemark(obj[3].toString());
				appleServer.setAsid((((obj[4].toString()))));
				appleServer.setInterType(obj[5].toString());
				appleServer.setInterAddress(obj[6].toString());
				appleServer.setInterMethod(obj[7].toString());
				appleServer.setUserName(obj[8].toString());
				appleServer.setDqM(obj[9].toString());
				list.add(appleServer);
			}
			resList.add(list);
			
			return resList;
			
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean isExistByTypeName(String appleName, String userName) {
		boolean flag=false;
		log.debug("finding all findByCode instances");
	    String hql = "from AppleServer app where app.userName='"+userName+"' and app.name='"+appleName+"'";
	    
	    List<UserMachineType> userMachineType=this.getHibernateTemplate().find(hql);
	    if(userMachineType.size()>0){
	    	flag = true;
	    }
	    return flag;
	}

}
